package com.ibl.rover.lite.client.Activity;

import java.text.MessageFormat;
import java.util.ArrayList;

import com.ibl.rover.lite.client.R;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.TextView;

public class DataSource extends ArrayAdapter<Item> {
	// private final MessageFormat PRICE_FORMAT;
	ArrayList<Item> myList = new ArrayList<Item>();

	public DataSource(Context context, int resource, int textViewResourceId) {
		super(context, resource, textViewResourceId);
		// PRICE_FORMAT = new MessageFormat(context.getResources().getText(
		// R.string.priceFormat).toString());
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Item subject = getItem(position);
		if (convertView == null) {
			LayoutInflater inflator = (LayoutInflater) getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflator.inflate(R.layout.item, null);

		} else {
			convertView.setTag(subject);
		}
		TextView nameCell = (TextView) convertView
				.findViewById(R.id.product_code);
		nameCell.setText(subject.getName());

		nameCell.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				v.setFocusableInTouchMode(true);
				v.requestFocus();

			}
		});

		TextView priceCell = (TextView) convertView
				.findViewById(R.id.product_price);
		Object parameters[] = new Object[] { Double.valueOf(subject.getPrice()) };
		priceCell.setText(subject.getPrice().toString());

		EditText editText = (EditText) convertView
				.findViewById(R.id.product_input);
		DatHolder datHolder = new DatHolder();
		if (editText.getTag() != null)
			editText.setText(((DatHolder) editText.getTag()).getQuantity());
		else
			editText.setTag(datHolder);

		editText.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				if (!hasFocus) {
					final int position = v.getId();
					((DatHolder) v.getTag()).setQuantity(((EditText) v)
							.getText().toString());

				}
			}
		});

		return convertView;
	}

}
